<template>
  <div class="app-form-list-wrapper">
    <div class="side">
      <div class="bar-button">
        <el-button @click="addNew" type="primary" size="small" icon="add" circle/>
      </div>

      <FList :selectedKey="selectedFormKey" title-name="menuName" :dataSource="formDefinition.menus"
             @select="selectMenu">
        <template v-slot:default="{item}">
          <div class="menu-list-item">
            <div style="flex: 1">{{ item.menuName }}</div>
            <div class="config-button" v-context="[menuContext, item]"
                 @click="(e) => showItemContext(e, item)">
              <el-button size="small" icon="setting" circle/>
            </div>
          </div>
        </template>
      </FList>
    </div>
    <div class="menu-config-content" v-if="!!edittingMenu">
      <div style="padding-right: 40px">
        <FSection title="基础设置">
          <el-form ref="formMenuConfigForm" label-width="160px" status-icon
                   :model="edittingMenu" :rules="rules">
            <el-form-item label="业务列表名称" prop="menuName">
              <el-input placeholder="请输入业务列表名称" v-model="edittingMenu.menuName"/>
            </el-form-item>

            <el-form-item label="列表显示项" prop="listField">
              <!--              <el-input placeholder="请选择业务列表名称" readonly-->
              <!--                        @click="selectListField" :value="getListFieldName()"/>-->

              <el-input placeholder="请选择业务列表名称" readonly @click="selectListField" :value="getListFieldName()"/>
            </el-form-item>

            <el-form-item label="排序设置">
              <el-input placeholder="请选择排序设置" @click="selectOrderByField" :value="getOrderByFeildName()"/>
            </el-form-item>

            <el-form-item label="自定义查询">
              <el-input placeholder="请选择自定义查询设置" @click="selectSearchField" :value="getSearchFeildName()"/>
            </el-form-item>

            <el-form-item label="操作范围">
              <el-button @click="openMenuActionRangConfiguration" round
                         v-if="isNotEmpty(edittingMenu.menuActionRanges)"
                         plain icon="ok" type="primary">点击设置操作范围</el-button>

              <el-button @click="openMenuActionRangConfiguration" round
                         v-else>点击设置操作范围</el-button>
            </el-form-item>

            <el-form-item label="pc视图" prop="detailPcViewId">
              <el-select v-model="edittingMenu.detailPcViewId"
                         class="m-2" placeholder="请选择视图">
                <el-option
                  v-for="item in formDefinition.views"
                  :key="item.id"
                  :label="item.viewName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item label="移动端视图" prop="detailMobileViewId">
              <el-select v-model="edittingMenu.detailMobileViewId"
                         class="m-2" placeholder="请选择视图">
                <el-option
                  v-for="item in formDefinition.views"
                  :key="item.id"
                  :label="item.viewName"
                  :value="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item label="备注信息">
              <el-input type="textarea" placeholder="请输入备注信息" v-model="edittingMenu.remark"/>
            </el-form-item>
          </el-form>
        </FSection>

        <FSection title="自定义按钮">
          <FormMenuButtonConfiguration
              :editingMenu="edittingMenu"
              :form-definition="formDefinition"
              ref="FormMenuButtonConfiguration"/>
        </FSection>

        <FSection title="开发设置">
          <el-form label-width="170px" status-icon :model="edittingMenu" :rules="rules"
                   ref="developConfigForm">
            <el-form-item label="自定义url(以'/'开头)" prop="listPageUrl">
              <el-input placeholder="请输入url" v-model="edittingMenu.listPageUrl"/>
            </el-form-item>
            <el-form-item label="列表组件(以'@/'开头)" prop="listPageComponent">
              <el-input placeholder="列表组件" v-model="edittingMenu.listPageComponent"/>
            </el-form-item>

            <el-form-item label="详情url(以'/'开头)" prop="detailPageUrl">
              <el-input placeholder="详情url" v-model="edittingMenu.detailPageUrl"/>
            </el-form-item>
            <el-form-item label="详情组件(以'@/'开头)" prop="detailPageComponent">
              <el-input placeholder="详情组件" v-model="edittingMenu.detailPageComponent"/>
            </el-form-item>
          </el-form>
        </FSection>
      </div>
      <div style="align-items: center; display: flex; justify-content: center">
        <el-button type="warning" round icon="cancel" @click="cancel">取消</el-button>
        <el-button type="primary" round @click="saveMenu" icon="ok">确定</el-button>
      </div>
    </div>

    <ListFieldConfig ref="ListFieldConfig" @selected="listFieldConfigSelected"/>
    <OrderByFieldConfig ref="OrderByFieldConfig" @selected="orderByFieldConfigSelected"/>
    <SearchFieldConfig ref="SearchFieldConfig" @selected="searchFieldConfigSelected"/>
    <MenuActionRangConfiguration ref="MenuActionRangConfiguration"/>
  </div>
</template>

<script>
import FList from '@/components/FList';
import {DefaultFormDefinition, DefaultMenuDefinition} from '@/components/form/DefaultFormDefinition';
import FSection from '@/components/FSection/index.vue';
import ListFieldConfig from '@/components/form/ListFieldConfig.vue';
import OrderByFieldConfig from '@/components/form/OrderByFieldConfig.vue';
import SearchFieldConfig from '@/components/form/SearchFieldConfig.vue';
import {guid, isEmpty, isNotEmpty, required} from '@/utils/CommonUtils';
import {reactive} from 'vue';
import MenuFactory from '@/components/app/menus/MenuFactory';
import FormDefinitionHelper from '@/components/form/FromDesigner/FormDefinitionHelper';
import {ElMessageBox} from 'element-plus';
import MenuActionRangConfiguration from '@/components/form/MenuActionRangConfiguration';
import FormMenuButtonConfiguration from '@/components/form/FormMenuButtonConfiguration';

export default {
  name: "FormMenuConfig",
  components: {
    FList,
    ListFieldConfig,
    OrderByFieldConfig,
    SearchFieldConfig,
    FormMenuButtonConfiguration,
    MenuActionRangConfiguration,
    FSection
  },
  data() {
    return {
      pcViewActionOptions: [],
      mobileViewActionOptions: [],
      rules: reactive({
        menuName: [required],
        listField: [required],
        detailPcViewId: [required],
        detailPcActionId: [required],
        detailMobileViewId: [required],
        detailMobileActionId: [required],

        listPageUrl: [required],
        listPageComponent: [required],
        detailPageUrl: [required],
        detailPageComponent: [required],
      }),
      menuContext: {
        width: 100,
        context: [
          {title: '上移', id: 'moveUp'},
          {title: '下移', id: 'moveDown'},
          {title: '删除', id: 'delete'},
        ],
        click: this.menuContextClick,
        close: () => null,
      },
      // edittingMenu: JSON.parse(JSON.stringify(DefaultMenuDefinition)),
      edittingMenu: undefined,
      selectedFormKey: undefined,
      formDefinition: JSON.parse(JSON.stringify(DefaultFormDefinition))
    };
  },
  methods: {
    isNotEmpty,
    setData(formDefinition) {
      this.formDefinition = formDefinition;
    },
    selectMenu(menu) {
      this.selectedFormKey = menu.id;
      this.edittingMenu = JSON.parse(JSON.stringify(menu));
      this.resolveFieldNames();
    },
    addNew() {
      if (isNotEmpty(this.edittingMenu)) {
        ElMessageBox.confirm('数据还未保存, 放弃编辑?', '放弃编辑?', {
          draggable: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.selectedFormKey = undefined;
          let factory = new MenuFactory(this.formDefinition.appId);
          let menu = JSON.parse(JSON.stringify(DefaultMenuDefinition));
          this.edittingMenu = factory.createDefaultFormMenuDefinition(menu, this.formDefinition);
          this.edittingMenu.formId = this.formDefinition.id;
        }).catch(() => {});
      } else {
        this.selectedFormKey = undefined;
        let factory = new MenuFactory(this.formDefinition.appId);
        let menu = JSON.parse(JSON.stringify(DefaultMenuDefinition));
        this.edittingMenu = factory.createDefaultFormMenuDefinition(menu, this.formDefinition);
        this.edittingMenu.formId = this.formDefinition.id;
      }
    },
    resolveFieldNames() {
      if (isEmpty(this.edittingMenu)) return;
      let helper = new FormDefinitionHelper(this.formDefinition);
      this.edittingMenu.listFieldName = helper.parseFieldNamesByNames(this.edittingMenu.listField);
    },
    cancel() {
      ElMessageBox.confirm('未保存的数据将会被丢弃', '确定取消吗', {
        draggable: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.clearSelected()
      }).catch(() => {
      });
    },
    saveMenu() {
      this.$refs.formMenuConfigForm.validate((valid, errors) => {
        if (valid) {
          this.$refs.FormMenuButtonConfiguration.checkButtons().then(() => {
            if (this.edittingMenu.id && this.edittingMenu.id !== '') {
              let index = this.formDefinition.menus.findIndex(m => m.id === this.edittingMenu.id);
              if (index !== -1) {
                this.formDefinition.menus[index] = this.edittingMenu;
              } else {
                this.formDefinition.menus.push(this.edittingMenu);
              }
              this.clearSelected();
            } else {
              this.edittingMenu.id = guid();
              this.formDefinition.menus.push(this.edittingMenu);
              this.clearSelected();
            }
          })
        } else {
          this.$message.warning('请将必填项填写完整');
        }
      });
    },
    clearSelected() {
      this.selectedFormKey = undefined;
      this.edittingMenu = undefined;
    },
    menuContextClick(item, menuItem) {
      if (item.id === 'delete') {
        this.removeMenuItem(menuItem);
      }
      this.menuContext.close();
    },
    removeMenuItem(menuItem) {
      ElMessageBox.confirm('确定删除吗?', '删除后无法恢复', {
        draggable: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let index = this.formDefinition.menus.findIndex(m => m.id === menuItem.id);
        if (index !== -1) {
          this.formDefinition.menus.splice(index, 1);
        }
        this.clearSelected();
      }).catch(() => {
      });
    },
    openMenuActionRangConfiguration() {
      this.$refs.MenuActionRangConfiguration.setData(this.edittingMenu, this.formDefinition);
    },
    selectSearchField() {
      this.$refs.SearchFieldConfig.setData(this.formDefinition, this.edittingMenu);
    },
    selectOrderByField() {
      this.$refs.OrderByFieldConfig.setData(this.formDefinition, this.edittingMenu);
    },
    selectListField() {
      this.$refs.ListFieldConfig.setData(this.formDefinition, this.edittingMenu);
    },
    searchFieldConfigSelected(selectedShowFields) {
      let temp = selectedShowFields.map(s => s.fieldName);
      temp = temp.join(',');
      this.edittingMenu.searchFields = temp;
    },
    orderByFieldConfigSelected(selectedShowFields) {
      let temp = selectedShowFields.map(s => s.fieldName);
      temp = temp.join(',');
      this.edittingMenu.orderBy = temp;

      temp = selectedShowFields.map(s => s.orderByType);
      temp = temp.join(',');
      this.edittingMenu.orderByType = temp;
    },
    listFieldConfigSelected(selectedShowFields) {
      let temp = selectedShowFields.map(s => s.fieldName);
      temp = temp.join(',');
      this.edittingMenu.listField = temp;
    },
    getSearchFeildName() {
      if (!this.edittingMenu || !this.edittingMenu.searchFields || this.edittingMenu.searchFields === '') return '';
      let helper = new FormDefinitionHelper(this.formDefinition);
      return helper.parseFieldNamesByNames(this.edittingMenu.searchFields);
    },
    getOrderByFeildName() {
      if (!this.edittingMenu || !this.edittingMenu.orderBy || this.edittingMenu.orderBy === '') return '';
      let helper = new FormDefinitionHelper(this.formDefinition);
      return helper.parseFieldNamesByNames(this.edittingMenu.orderBy);
    },
    getListFieldName() {
      if (!this.edittingMenu || !this.edittingMenu.listField || this.edittingMenu.listField === '') return '';
      let helper = new FormDefinitionHelper(this.formDefinition);
      return helper.parseFieldNamesByNames(this.edittingMenu.listField);
    },
    showItemContext(e, item) {

    },
  }
};
</script>

<style scoped>
.app-form-list-wrapper {
  height: calc(100vh - 40px);
  display: flex;
}

.app-form-list-wrapper .content {
  position: relative;
}

.app-form-list-wrapper .side {
  height: calc(100vh - 40px);
  overflow: visible;
  width: 260px;
  position: relative;
  z-index: 10;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
  background: white;
}

.app-form-list-wrapper .bar-button {
  position: absolute;
  top: 8px;
  right: -14px;
  z-index: 10;
  height: 25px;
  width: 25px;
}

.app-form-list-wrapper .menu-list-item {
  display: flex;
  width: 100%;
}

.app-form-list-wrapper .config-button {
  width: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.app-form-list-wrapper .menu-config-content {
  padding-top: 30px;
  padding-left: 40px;
  padding-bottom: 50px;
  height: calc(100vh - 40px);
  overflow: auto;
  width: calc(100vw - 250px);
  background: white;
  margin-left: 10px;
  box-sizing: border-box;
}
</style>
